package integrity;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Signature;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

public class SignKey {

	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub

		//Generating the assymetric secret key
		KeyGenerator kg = KeyGenerator.getInstance("AES");
		kg.init(128);
		SecretKey k = kg.generateKey();
		
	    //Generate Public and Private key
	    System.out.println("Generating your public and private key");
	    KeyPairGenerator keyParGen = KeyPairGenerator.getInstance("RSA");
	    
	    SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
	    keyParGen.initialize(1024, random);
	    
	    KeyPair pair = keyParGen.generateKeyPair();
	    PrivateKey privateKey = pair.getPrivate();
	    PublicKey publicKey = pair.getPublic();
	    
	    //Generating the signature and signing it with the privateKey
	    Signature signedSignature = Signature.getInstance("SHA1withRSA");
	    signedSignature.initSign(privateKey);
	    FileInputStream loadedEnctryptedFile = new FileInputStream("credentials.txt");
	    BufferedInputStream bufin = new BufferedInputStream(loadedEnctryptedFile);
	    byte[] buffer = new byte[1024];
	    int len;
	    while ((len = bufin.read(buffer)) >= 0) {
	    	signedSignature.update(buffer, 0, len);
	    };
	    bufin.close();
	    byte[] realSignature = signedSignature.sign();
	    
	    //Saving the signed file
	    FileOutputStream signedFileOut = new FileOutputStream("credentials_signed.txt");
	    signedFileOut.write(realSignature);
	    System.out.println("Signed file saved...");
	    signedFileOut.close();
	    
	    //Saving the public key file
	    byte[] publicKeyEncode = publicKey.getEncoded();
	    FileOutputStream publicKeyOut = new FileOutputStream("PublicKey." +"publicKey");
	    publicKeyOut.write(publicKeyEncode);
	    System.out.println("Public key saved...");
	    
	}
	
	
	

}
